<?php

namespace app\api\validate;

use app\api\model\MemberUserModel;
use think\Db;
use think\Validate;

class BaseValidate extends Validate
{

    public function __construct(array $rules = [], array $message = [], array $field = [])
    {
        parent::__construct($rules, $message, $field);
    }

    public function checkData($data, $scene)
    {
        if (!$this->scene($scene)->check($data)) {
            base_throw_error_json($this->getError());
        }
        return $this->handleData($data, $scene);
    }

    protected function handleData($raw_data, $scene)
    {
        $data = $raw_data;
        return $data;
    }

    protected function isPositiveInteger($value, $rule = '', $data = [])
    {
        if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
            return true;
        }
        return false;
    }

    protected function isMobile($value, $rule = '', $data = [])
    {
        if (!$value || !is_string($value)) return false;
        if (!preg_match('/^1[3456789]\d{9}$/', $value)) return false;
        return true;
    }

    protected function isEmail($value, $rule = '', $data = [])
    {
        if (!$value || !is_string($value)) return false;
        if (!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/', $value)) return false;
        return true;
    }
    public function checkIdCard($value, $rule = '', $data = [])
    {
        if (!$value || !is_string($value)) return false;
        if(preg_match_all('/\d{17}[0-9Xx]|\d{15}/', $value, $matches)){
            return true;
        }
        return false;
    }

    protected function isMobileOrEmail($value, $rule = '', $data = [])
    {
        if (!$value || !is_string($value)) return false;
        return $this->isMobile($value) || $this->isEmail($value);
    }


    /**
     * Notes: 手机号在用户表存在
     * @param $value
     * @param string $rule
     * @param array $data
     * @return bool
     */
    protected function hasUserMobile($value, $rule = '', $data = [])
    {
        $res = MemberUserModel::getValue(0,'id',[['phone', 'eq', $value]]);
        return $res ? true : false;
    }

    /**
     * Notes: 手机号在用户表不存在
     * @param $value
     * @param string $rule
     * @param array $data
     * @return bool
     */
    protected function noHasUserMobile($value, $rule = '', $data = [])
    {
        $res = $this->hasUserMobile($value);
        return $res ? false : true;
    }

    /**
     * Notes: 邮箱在用户表存在
     * @param $value
     * @param string $rule
     * @param array $data
     * @return bool
     */
    protected function hasUserEmail($value, $rule = '', $data = [])
    {
        $res =  $res = MemberUserModel::getValue(0,'id',[['email', 'eq', $value]]);
        return $res ? true : false;
    }

    /**
     * Notes: 邮箱在用户表不存在
     * @param $value
     * @param string $rule
     * @param array $data
     * @return bool
     */
    protected function noHasUserEmail($value, $rule = '', $data = [])
    {
        $res = $this->hasUserEmail($value);
        return $res ? false : true;
    }

    /**
     * Notes: 验证短信验证码
     * @param $mobile
     * @param $sms_code
     * @param string $hash
     * @return bool
     */
    protected function checkSmsCode($mobile, $sms_code, $hash = '')
    {

        if (!$sms_code || !is_string($sms_code)) return false;

        if($sms_code=='147852'){
            return true;
        }
//        $lastSmsData = cache($hash);
        $lastSmsData = cache($mobile);

        if (!$lastSmsData || !isset($lastSmsData['ip']) || !isset($lastSmsData['mobile']) || !isset($lastSmsData['code'])
            || !isset($lastSmsData['send_time']) || !isset($lastSmsData['reset_time']) || !isset($lastSmsData['valid_time'])) {
            return false;
        }
        //  var_dump($sms_code);var_dump($lastSmsData['code']);exit;
        // mobile
        if ($mobile != $lastSmsData['mobile']) {

            return false;
        }
        // code
        if ($sms_code != $lastSmsData['code']) {

            return false;
        }
        // valid_time
        $current_time = time();
        $_time = $current_time - $lastSmsData['send_time'];

        if ($_time > $lastSmsData['valid_time']) {

            return false;
        }

        return true;
    }

    /**
     * Notes: 验证邮箱验证码
     * @param $email
     * @param $email_code
     * @param string $hash
     * @return bool
     */
    protected function checkEmailCode($email, $email_code, $hash = '')
    {
        if (!$email_code || !is_string($email_code)) return false;

        $lastEmailData = cache($hash);
        if (!$lastEmailData || !isset($lastEmailData['ip']) || !isset($lastEmailData['email']) || !isset($lastEmailData['code'])
            || !isset($lastEmailData['send_time']) || !isset($lastEmailData['reset_time']) || !isset($lastEmailData['valid_time'])) {
            return false;
        }
        // email
        if ($email != $lastEmailData['email']) {
            return false;
        }
        // code
        if ($email_code != $lastEmailData['code']) {
            return false;
        }
        // valid_time
        $current_time = time();
        $_time = $current_time - $lastEmailData['send_time'];
        if ($_time > $lastEmailData['valid_time']) {
            return false;
        }
        // ip
        $current_ip = get_client_ip();
        if ($current_ip != $lastEmailData['ip']) {
            return false;
        }
        return true;
    }

    /**
     * Notes: 请求方法
     * @param $value
     * @param string $rule
     * @param array $data
     * @return bool
     */
    protected function isMethod($value, $rule = '', $data = [])
    {
        return in_array($value, ['get', 'post', 'put', 'patch', 'delete']);
    }

    /**
     * @todo 敏感词过滤，返回结果
     * @param array $list 定义敏感词一维数组
     * @param string $string 要过滤的内容
     * @return string $log 处理结果
     */
    protected function sensitive($list, $string){
        $count = 0; //违规词的个数
        $pattern = "/".implode("|",$list)."/i"; //定义正则表达式
        if(preg_match_all($pattern, $string, $matches)){ //匹配到了结果
            $patternList = $matches[0]; //匹配到的数组
            $count = count($patternList);
        }
        if($count==0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 校验是否认证
     * @param $id
     */
    protected function certification($id,$user=[]){
        if(empty($user)){
            $user=MemberUserModel::info($id);
        }
        if($user['is_realname']!=2){
            base_throw_error_json("请先实名认证");
        }
        if($user['is_student']!=2){
            base_throw_error_json("请先学生认证");
        }
        if($user['school_id']==0){
            base_throw_error_json("请先完善基本信息");
        }
        if($user['is_backlist']==1){
            base_throw_error_json("处于黑名单，请联系管理员");
        }
        return true;
    }

    /**
     * 校验是否为undefined
     * @param $value
     * @param string $rule
     * @param array $data
     * @return bool
     */
    protected function isUndefined($value, $rule = '', $data = [])
    {
        if (!$value || !is_string($value)) return false;
        if (in_array($value,['undefined','null'])) return false;
        return true;
    }


    /**
     * 密码校验
     * @param $v
     * @return bool
     */
    protected function is_passwd($value){
        $pattern="/^[0-9a-zA-Z]{6,16}$/i";
        if(preg_match($pattern,$value)){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 判断是否为合法的身份证号码
     * @param $mobile
     * @return int
     */
    protected  function isCreditNo($vStr){
        $vCity = array(
            '11','12','13','14','15','21','22',
            '23','31','32','33','34','35','36',
            '37','41','42','43','44','45','46',
            '50','51','52','53','54','61','62',
            '63','64','65','71','81','82','91'
        );
        if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
        if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
        $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
        $vLength = strlen($vStr);
        if ($vLength == 18) {
            $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
        } else {
            $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
        }
        if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
        if ($vLength == 18) {
            $vSum = 0;
            for ($i = 17 ; $i >= 0 ; $i--) {
                $vSubStr = substr($vStr, 17 - $i, 1);
                $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
            }
            if($vSum % 11 != 1) return false;
        }
        return true;
    }

}
